<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>任务发布测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 600px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .header {
            background: #007AFF;
            color: white;
            padding: 20px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 24px;
            margin-bottom: 8px;
        }
        
        .header p {
            opacity: 0.9;
            font-size: 14px;
        }
        
        .form-container {
            padding: 30px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }
        
        .form-input, .form-select, .form-textarea {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s;
        }
        
        .form-input:focus, .form-select:focus, .form-textarea:focus {
            outline: none;
            border-color: #007AFF;
        }
        
        .form-textarea {
            resize: vertical;
            min-height: 100px;
        }
        
        .upload-area {
            border: 2px dashed #ddd;
            border-radius: 8px;
            padding: 30px;
            text-align: center;
            background: #fafafa;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .upload-area:hover {
            border-color: #007AFF;
            background: #f0f8ff;
        }
        
        .upload-area.dragover {
            border-color: #007AFF;
            background: #f0f8ff;
        }
        
        .upload-icon {
            width: 40px;
            height: 40px;
            margin: 0 auto 15px;
            background: #007AFF;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 20px;
        }
        
        .upload-text {
            font-size: 16px;
            color: #333;
            margin-bottom: 8px;
        }
        
        .upload-hint {
            font-size: 12px;
            color: #666;
        }
        
        .file-input {
            display: none;
        }
        
        .file-preview {
            margin-top: 15px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .file-item {
            position: relative;
            border: 1px solid #ddd;
            border-radius: 6px;
            padding: 8px 12px;
            background: white;
            font-size: 12px;
            color: #666;
        }
        
        .file-remove {
            position: absolute;
            top: -5px;
            right: -5px;
            width: 18px;
            height: 18px;
            background: #ff4757;
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .btn-group {
            display: flex;
            gap: 15px;
            margin-top: 30px;
        }
        
        .btn {
            flex: 1;
            padding: 15px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background: #007AFF;
            color: white;
        }
        
        .btn-primary:hover {
            background: #0056b3;
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .status-info {
            margin-top: 20px;
            padding: 15px;
            border-radius: 8px;
            font-size: 14px;
        }
        
        .status-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .status-info.hidden {
            display: none;
        }
        
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #007AFF;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>任务发布测试</h1>
            <p>简化版任务发布接口测试页面</p>
        </div>
        
        <div class="form-container">
            <form id="taskForm">
                <!-- 任务分类 -->
                <div class="form-group">
                    <label class="form-label">任务分类 *</label>
                    <select id="categoryId" name="categoryId" class="form-select" required>
                        <option value="">请选择任务分类</option>
                    </select>
                </div>
                
                <!-- 任务描述 -->
                <div class="form-group">
                    <label class="form-label">任务描述 *</label>
                    <textarea id="taskDescription" name="taskDescription" class="form-textarea" 
                              placeholder="请详细描述任务内容、要求等..." required></textarea>
                </div>
                
                <!-- 任务图片 -->
                <div class="form-group">
                    <label class="form-label">任务图片</label>
                    <div class="upload-area" id="uploadArea">
                        <div class="upload-icon">📷</div>
                        <div class="upload-text">点击或拖拽上传图片</div>
                        <div class="upload-hint">支持 JPG、PNG、WEBP 格式，最多5张</div>
                    </div>
                    <input type="file" id="fileInput" class="file-input" accept="image/*" multiple>
                    <div class="file-preview" id="filePreview"></div>
                </div>
                
                <!-- 状态信息 -->
                <div id="statusInfo" class="status-info hidden"></div>
                
                <!-- 按钮组 -->
                <div class="btn-group">
                    <button type="button" class="btn btn-secondary" onclick="resetForm()">重置</button>
                    <button type="submit" class="btn btn-primary" id="submitBtn">发布任务</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let uploadedImages = [];
        
        // 页面加载时获取任务分类
        document.addEventListener('DOMContentLoaded', function() {
            loadCategories();
            initFileUpload();
        });
        
        // 加载任务分类
        async function loadCategories() {
            try {
                const response = await fetch('/drone/taskSimple/categories');
                const result = await response.json();
                
                if (result.code === 200) {
                    const select = document.getElementById('categoryId');
                    result.data.forEach(category => {
                        const option = document.createElement('option');
                        option.value = category.categoryId;
                        option.textContent = category.categoryName;
                        select.appendChild(option);
                    });
                } else {
                    showStatus('加载分类失败: ' + result.msg, 'error');
                }
            } catch (error) {
                showStatus('加载分类失败: ' + error.message, 'error');
            }
        }
        
        // 初始化文件上传
        function initFileUpload() {
            const uploadArea = document.getElementById('uploadArea');
            const fileInput = document.getElementById('fileInput');
            
            // 点击上传区域
            uploadArea.addEventListener('click', () => {
                fileInput.click();
            });
            
            // 文件选择
            fileInput.addEventListener('change', handleFileSelect);
            
            // 拖拽上传
            uploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadArea.classList.add('dragover');
            });
            
            uploadArea.addEventListener('dragleave', () => {
                uploadArea.classList.remove('dragover');
            });
            
            uploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadArea.classList.remove('dragover');
                const files = e.dataTransfer.files;
                handleFiles(files);
            });
        }
        
        // 处理文件选择
        function handleFileSelect(e) {
            const files = e.target.files;
            handleFiles(files);
        }
        
        // 处理文件
        function handleFiles(files) {
            const fileArray = Array.from(files);
            const imageFiles = fileArray.filter(file => file.type.startsWith('image/'));
            
            if (imageFiles.length === 0) {
                showStatus('请选择图片文件', 'error');
                return;
            }
            
            if (uploadedImages.length + imageFiles.length > 5) {
                showStatus('最多只能上传5张图片', 'error');
                return;
            }
            
            // 上传文件
            imageFiles.forEach(file => {
                uploadFile(file);
            });
        }
        
        // 上传单个文件
        async function uploadFile(file) {
            const formData = new FormData();
            formData.append('file', file);
            
            try {
                const response = await fetch('/drone/task/upload/image', {
                    method: 'POST',
                    body: formData
                });
                
                console.log('图片上传响应状态:', response.status);
                console.log('图片上传响应头:', response.headers);
                
                const result = await response.json();
                console.log('图片上传响应:', result);
                
                if (result.code === 200) {
                    uploadedImages.push(result.msg);
                    console.log('图片上传成功 - 添加到数组:', result.msg);
                    console.log('当前uploadedImages数组:', uploadedImages);
                    updateFilePreview();
                    showStatus('图片上传成功', 'success');
                } else {
                    showStatus('图片上传失败: ' + result.msg, 'error');
                }
            } catch (error) {
                showStatus('图片上传失败: ' + error.message, 'error');
            }
        }
        
        // 更新文件预览
        function updateFilePreview() {
            const preview = document.getElementById('filePreview');
            preview.innerHTML = '';
            
            uploadedImages.forEach((imageUrl, index) => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                fileItem.innerHTML = `
                    <span>图片${index + 1}</span>
                    <button class="file-remove" onclick="removeFile(${index})">×</button>
                `;
                preview.appendChild(fileItem);
            });
        }
        
        // 删除文件
        function removeFile(index) {
            uploadedImages.splice(index, 1);
            updateFilePreview();
        }
        
        // 表单提交
        document.getElementById('taskForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const categoryId = document.getElementById('categoryId').value;
            const taskDescription = document.getElementById('taskDescription').value;
            
            if (!categoryId) {
                showStatus('请选择任务分类', 'error');
                return;
            }
            
            if (!taskDescription.trim()) {
                showStatus('请输入任务描述', 'error');
                return;
            }
            
            // 检查是否已登录
            const token = localStorage.getItem('token');
            console.log('任务发布页面 - 获取到的token:', token);
            if (!token) {
                showStatus('请先登录', 'error');
                return;
            }
            
            // 显示加载状态
            const submitBtn = document.getElementById('submitBtn');
            const originalText = submitBtn.textContent;
            submitBtn.innerHTML = '<div class="loading"></div> 发布中...';
            submitBtn.disabled = true;
            
            try {
                console.log('提交任务 - uploadedImages:', uploadedImages);
                console.log('提交任务 - taskImages JSON:', JSON.stringify(uploadedImages));
                
                const taskData = {
                    categoryId: parseInt(categoryId),
                    taskDescription: taskDescription,
                    taskImages: JSON.stringify(uploadedImages)
                };
                
                const response = await fetch('/drone/taskSimple/publish', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + token
                    },
                    body: JSON.stringify(taskData)
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    showStatus('任务发布成功！', 'success');
                    resetForm();
                } else {
                    if (result.code === 401) {
                        showStatus('登录已过期，请重新登录', 'error');
                        setTimeout(() => {
                            window.location.href = '/login.html';
                        }, 2000);
                    } else {
                        showStatus('任务发布失败: ' + result.msg, 'error');
                    }
                }
            } catch (error) {
                showStatus('网络错误: ' + error.message, 'error');
            } finally {
                // 恢复按钮状态
                submitBtn.textContent = originalText;
                submitBtn.disabled = false;
            }
        });
        
        // 重置表单
        function resetForm() {
            document.getElementById('taskForm').reset();
            uploadedImages = [];
            updateFilePreview();
            hideStatus();
        }
        
        // 显示状态信息
        function showStatus(message, type) {
            const statusInfo = document.getElementById('statusInfo');
            statusInfo.textContent = message;
            statusInfo.className = `status-info status-${type}`;
            statusInfo.classList.remove('hidden');
            
            // 3秒后自动隐藏成功消息
            if (type === 'success') {
                setTimeout(() => {
                    hideStatus();
                }, 3000);
            }
        }
        
        // 隐藏状态信息
        function hideStatus() {
            const statusInfo = document.getElementById('statusInfo');
            statusInfo.classList.add('hidden');
        }
        
        // 检查登录状态
        function checkLoginStatus() {
            const token = localStorage.getItem('token');
            const userType = localStorage.getItem('userType');
            
            console.log('任务发布页面加载 - token:', token);
            console.log('任务发布页面加载 - userType:', userType);
            
            if (!token) {
                showStatus('请先登录才能发布任务', 'error');
                setTimeout(() => {
                    window.location.href = '/login.html';
                }, 2000);
                return false;
            }
            
            if (userType !== '2') {
                showStatus('只有组织方可以发布任务', 'error');
                setTimeout(() => {
                    window.location.href = '/login.html';
                }, 2000);
                return false;
            }
            
            return true;
        }
        
        // 页面加载时检查登录状态
        document.addEventListener('DOMContentLoaded', function() {
            if (checkLoginStatus()) {
                loadCategories();
                initFileUpload();
            }
        });
    </script>
</body>
</html>
